package top.szhome.system.config;

import com.baomidou.mybatisplus.extension.plugins.inner.BaseMultiTableInnerInterceptor;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.ExpressionVisitorAdapter;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.LikeExpression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.statement.values.ValuesStatement;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 唐加利
 * @date 2023/9/28
 */
public class LikeEscapeInterceptor extends BaseMultiTableInnerInterceptor {

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        String sql = boundSql.getSql();
        try {
            Select parse = (Select) CCJSqlParserUtil.parse(sql);
            SelectBody selectBody = parse.getSelectBody();
            selectBody.accept(new SelectVisitorAdapter() {
                @Override
                public void visit(PlainSelect plainSelect) {
                    Expression where = plainSelect.getWhere();
                    where.accept(new ExpressionVisitorAdapter() {
                        @Override
                        public void visit(LikeExpression expr) {
                            Expression right = expr.getRightExpression();
                            String value = right.toString();
                            value.replaceAll("(?!^)([%?])(?!$)", "\\\\$1");
                            expr.setRightExpression(new StringValue(value));
                        }
                    });
                }
            });
        } catch (JSQLParserException e) {

        }
    }

    @Override
    public Expression buildTableExpression(Table table, Expression where, String whereSegment) {
        return null;
    }
}
